<script setup>
import { ref, watch, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { queryEmpApi, addEmpApi, queryEmpById, updateEmpApi, deleteEmpByIdsApi } from '@/api/emp'
import { getAllDept as deptSearch } from '@/api/dept'

//声明token
const token = ref('')

//钩子函数 挂载
onMounted(() => {
  search();
  updateDeptList();
  getToken();
}
)
//获取token
const getToken = () => {
  const loginUser = JSON.parse(localStorage.getItem('loginUser'));
  if(loginUser && loginUser.token){
    token.value = loginUser.token;
  }
}

//输入查询的员工
const searchEmp = ref({ name: '', gender: '', data: [], begin: '', end: '' });

//侦听data
watch(() => searchEmp.value.data, (newVal, oldVal) => {
  if (newVal.length == 2) {
    searchEmp.value.begin = newVal[0];
    searchEmp.value.end = newVal[1];
  }
})
//查询操作
const search = async () => {
  const result = await queryEmpApi(
    searchEmp.value.name,
    searchEmp.value.gender,
    searchEmp.value.begin,
    searchEmp.value.end,
    currentPage.value,
    pageSize.value
  )
  if (result.code) {
    //查询成功
    //接收数据
    empList.value = result.data.rows;
    total.value = result.data.total;
  } else {
    //查询失败
    ElMessage.danger(result.msg);
  }
}
//清空操作
const clear = () => {
  searchEmp.value = { name: '', gender: '', data: [], begin: '', end: '' };
  search();
}

//员工数据表格展示
const empList = ref([]);

// 分页
const currentPage = ref(1); //页码
const pageSize = ref(10);  //每页展示数据量
const background = ref(true);//是否开启背景色
const total = ref(0); //总记录数
//每页展示记录数发生变化触发
const handleSizeChange = (val) => {
  search();
}
//页码发生变化触发
const handleCurrentChange = (val) => {
  search();
}



//---------- 新增员工
const employee = ref({
  image: '',
  username: '',
  name: '',
  gender: '',
  job: '',
  entryDate: '',
  deptId: '',
  phone: '',
  salary: '',
  exprList: [],
});

const dialogVisible = ref(false);
const dialogTitle = ref('');
//职位列表数据
const jobs = ref([{ name: '班主任', value: 1 }, { name: '讲师', value: 2 }, { name: '学工主管', value: 3 }, { name: '教研主管', value: 4 }, { name: '咨询师', value: 5 }, { name: '其他', value: 6 }])
//性别列表数据
const genders = ref([{ name: '男', value: 1 }, { name: '女', value: 2 }])
//部门列表数据
const deptList = ref([])
const empFormRef = ref();
const updateDeptList = async () => {
  const result = await deptSearch();
  if (result.code) {
    //成功 查询部门列表数据 
    deptList.value = result.data
  } else {
    ElMessage.error(result.msg);
  }
}
//文件上传之后的处理
const handleAvatarSuccess = (response) => {
  employee.value.image = response.data;
}

//文件上传之前的处理
const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error('只支持文件上传')
    return false
  } else if (rawFile.size / 1024 / 1024 > 10) {
    ElMessage.error('上传的图片大小不能超过10M')
    return false
  }
  return true
}

const addEmp = () => {
  dialogTitle.value = '新增员工';
  dialogVisible.value = true;

  //清空员工数据
  employee.value = {
    image: '',
    username: '',
    name: '',
    gender: '',
    job: '',
    entryDate: '',
    deptId: '',
    phone: '',
    salary: '',
    exprList: [],
  }
  //清空校验信息
  if (empFormRef.value) {
    empFormRef.value.resetFields();
  }
}

const addExpr = () => {
  employee.value.exprList.push({ company: '', job: '', begin: '', end: '', timeData: [] })
}
const deleteExpr = (index) => {
  employee.value.exprList.splice(index, 1);
}

//侦听employee.value.exprList
watch(() => employee.value.exprList, (newVal, oldVal) => {
  newVal.forEach(expr => {
    if (expr.timeData.length > 0 && expr.timeData) {
      expr.begin = expr.timeData[0];
      expr.end = expr.timeData[1];
    }
  })
}, { deep: true })

//表单校验
const rules = ref({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名长度应在2到20个字符之间', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '姓名长度应在2到10个字符之间', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号', trigger: 'blur' }
  ]
});

const saveEmp = () => {
  if (!empFormRef.value) { return; }
  empFormRef.value.validate(async (valid) => {
    if (valid) {
      //表单校验成功
      let result;
      //判断是 新增还是编辑
      if (employee.value.id) {
        //有值 编辑
        result = await updateEmpApi(employee.value)
      } else {
        //无值 新增
        result = await addEmpApi(employee.value);
      }

      if (result.code) {
        //添加成功
        ElMessage.success('保存员工成功');
        dialogVisible.value = false;
        search();
      } else {
        //添加失败
        ElMessage.error(result.msg);
        dialogVisible.value = false;
      }
    } else {
      //表单校验失败
      ElMessage.error('表单校验失败 请检查输入')
    }
  })
}
//--------编辑员工
const editEmp = async (id) => {
  //查询回显
  const result = await queryEmpById(id);
  if (result.code) {
    //查询成功 赋值epolyee
    dialogTitle.value = '编辑员工';
    dialogVisible.value = true;
    employee.value = result.data;
  } else {
    //失败
    ElMessage.error(result.msg);
  }

  //处理 返回来的员工经历
  const empExprList = employee.value.exprList;
  if (empExprList && empExprList.length > 0) {
    empExprList.forEach(expr => {
      expr.timeData = [expr.begin, expr.end]
    })
  }
}

//-------------删除员工
const deleteEmpById = async (id) => {
  //确认是否删除
  ElMessageBox.confirm(
    '是否确认删除该员工?',
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => { //确认后执行
      const result = await deleteEmpByIdsApi(id);
      if (result.code) {
        //删除成功
        ElMessage.success('删除成功');
        search();
      } else {
        //删除失败
        ElMessage.error(result.msg);
      }
    })
    .catch(() => { //取消后执行
      ElMessage.info('删除已取消');
    })
}

let ids = [];

//复选框选中之后触发
const handleSelectionChange = (selection) => {
  ids = selection.map(item => item.id)
}

const deleteEmpByIds = async () => {
  //确认是否删除
  ElMessageBox.confirm(
    '是否确认删除所选员工?',
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => { //确认后执行
        //判断有无勾选
        if (ids.length === 0) {
          ElMessage.warning('请选择要删除的项');
          return;
        }
      const result = await deleteEmpByIdsApi(ids);
      if (result.code) {
        //删除成功
        ElMessage.success('删除成功');
        search();
      } else {
        //删除失败
        ElMessage.error(result.msg);
      }
    })
    .catch(() => { //取消后执行
      ElMessage.info('删除已取消');
    })
}

</script>

<template>

  <h1>员工管理</h1>
  <div class="container">

    <!-- 搜索框 -->
    <el-form :inline="true" :model="searchEmp" class="demo-form-inline">

      <el-form-item label="姓名">
        <el-input v-model="searchEmp.name" placeholder="请输入姓名" />
      </el-form-item>

      <el-form-item label="性别">
        <el-select v-model="searchEmp.gender" placeholder="请选择">
          <el-option label="男" value="1" />
          <el-option label="女" value="2" />
        </el-select>
      </el-form-item>

      <el-form-item label="入职日期">
        <el-date-picker v-model="searchEmp.data" type="datetimerange" range-separator="到" start-placeholder="开始日期"
          end-placeholder="结束日期" value-format="YYYY-MM-DD" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="search">查询</el-button>
        <el-button type="info" @click="clear">清空</el-button>
      </el-form-item>
    </el-form>
  </div>

  <!-- 新增-批量删除按钮 -->
  <div class="container">
    <el-button type="primary" @click="addEmp">+ 新增员工</el-button>
    <el-button type="danger" @click="deleteEmpByIds">- 批量删除</el-button>
  </div>

  <!-- 员工数据表格展示 -->
  <div class="container">
    <el-table :data="empList" border style="width: 100%" @selection-change="handleSelectionChange">
      <!-- 复选框 -->
      <el-table-column type="selection" width="55" />
      <el-table-column prop="name" label="姓名" width="120" align="center" />
      <el-table-column label="性别" width="120" align="center">
        <template #default="scope">
          {{ scope.row.gender == 1 ? '男' : '女' }}
        </template>
      </el-table-column>
      <el-table-column label="头像" width="120" align="center">
        <template #default="scope">
          <img :src="scope.row.image" height="40px"></img>
        </template>
      </el-table-column>
      <el-table-column prop="deptName" label="所属部门" width="120" align="center" />
      <el-table-column prop="job" label="职位" width="120" align="center">
        <template #default="scope">
          <span v-if="scope.row.job == 1">班主任</span>
          <span v-else-if="scope.row.job == 2">讲师</span>
          <span v-else-if="scope.row.job == 3">学工主管</span>
          <span v-else-if="scope.row.job == 4">教研主管</span>
          <span v-else-if="scope.row.job == 5">咨询师</span>
          <span v-else>其它</span>
        </template>
      </el-table-column>
      <el-table-column prop="entryDate" label="入职日期" width="180" align="center" />
      <el-table-column prop="updateTime" label="最后操作时间" width="180" align="center" />
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button type="primary" round @click="editEmp(scope.row.id)">
            <el-icon>
              <Edit />
            </el-icon>编辑</el-button>
          <el-button type="danger" round @click="deleteEmpById(scope.row.id)">
            <el-icon>
              <Delete />
            </el-icon>删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>

  <!-- 分页条 -->
  <div class="container">
    <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 30, 40, 50]"
      :background="background" layout="total, sizes, prev, pager, next, jumper" :total="total"
      @size-change="handleSizeChange" @current-change="handleCurrentChange" />
  </div>

  <!-- 新增/修改员工的对话框 -->
  <el-dialog v-model="dialogVisible" :title="dialogTitle" transition="dialog-bounce">
    <el-form :model="employee" label-width="80px" :rules="rules" ref="empFormRef">
      <!-- 基本信息 -->
      <!-- 第一行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="employee.username" placeholder="请输入员工用户名"></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="employee.name" placeholder="请输入员工姓名"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第二行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="性别" prop="gender">
            <el-select v-model="employee.gender" placeholder="请选择性别" style="width: 100%;">
              <el-option v-for="gender in genders" :key="gender.value" :label="gender.name" :value="gender.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="employee.phone" placeholder="请输入员工手机号"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第三行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="职位">
            <el-select v-model="employee.job" placeholder="请选择职位" style="width: 100%;">
              <el-option v-for="job in jobs" :key="job.value" :label="job.name" :value="job.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="薪资">
            <el-input v-model="employee.salary" placeholder="请输入员工薪资"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第四行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="所属部门">
            <el-select v-model="employee.deptId" placeholder="请选择部门" style="width: 100%;">
              <el-option v-for="dept in deptList" :key="dept.id" :label="dept.name" :value="dept.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="入职日期">
            <el-date-picker v-model="employee.entryDate" type="date" style="width: 100%;" placeholder="选择日期"
              format="YYYY-MM-DD" value-format="YYYY-MM-DD"></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第五行 -->
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="头像">
            <el-upload 
            :headers="{'token': token}"
            class="avatar-uploader" 
            action="/api/upload" 
            :show-file-list="false"
            :on-success="handleAvatarSuccess" 
            :before-upload="beforeAvatarUpload">
            <img v-if="employee.image" :src="employee.image" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>


      <!-- 工作经历 -->
      <!-- 第六行 -->
      <el-row :gutter="10">
        <el-col :span="24">
          <el-form-item label="工作经历">
            <el-button type="success" size="small" @click="addExpr">+ 添加工作经历</el-button>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第七行 ...  工作经历 -->
      <el-row :gutter="3" v-for="(expr, index) in employee.exprList">
        <el-col :span="10">
          <el-form-item size="small" label="时间" label-width="80px">
            <el-date-picker type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
              format="YYYY-MM-DD" value-format="YYYY-MM-DD" v-model="expr.timeData"></el-date-picker>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item size="small" label="公司" label-width="60px">
            <el-input placeholder="请输入公司名称" v-model="expr.company"></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item size="small" label="职位" label-width="60px">
            <el-input placeholder="请输入职位" v-model="expr.job"></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="2">
          <el-form-item size="small" label-width="0px">
            <el-button type="danger" @click="deleteExpr(index)">- 删除</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 底部按钮 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveEmp">保存</el-button>
      </span>
    </template>
  </el-dialog>






</template>

<style scoped>
.container {
  margin: 15px 0px;
}

.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}


.avatar {
  height: 40px;
}

.avatar-uploader .avatar {
  width: 78px;
  height: 78px;
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 78px;
  height: 78px;
  text-align: center;
  border-radius: 10px;
  /* 添加灰色的虚线边框 */
  border: 1px dashed var(--el-border-color);
}

/* Bounce Animation */
.dialog-bounce-enter-active,
.dialog-bounce-leave-active,
.dialog-bounce-enter-active .el-dialog,
.dialog-bounce-leave-active .el-dialog {
  transition: all 0.5s cubic-bezier(0.175, 0.885, 0.32, 1.275);
}

.dialog-bounce-enter-from,
.dialog-bounce-leave-to {
  opacity: 0;
}

.dialog-bounce-enter-from .el-dialog,
.dialog-bounce-leave-to .el-dialog {
  transform: scale(0.3) translateY(-50px);
  opacity: 0;
}
</style>
